<?php
/**
 * A mail extension for yii
 *
 * Based on smtp protocol
 *
 * @link      http://github.com/tlikai/teaconf
 * @author    likai<youyuge@gmail.com>
 * @license   http://www.teaconf.com/license New BSD License
 */

require dirname(__FILE__) . DIRECTORY_SEPARATOR .  'Mailer.php';

class SmtpMailer extends Mailer
{
    /**
     * Smtp server address
     *
     * @var string
     */
    public $server;

    /**
     * Smtp server port
     *
     * @var integer
     */
    public $port = 25;

    /**
     * Connecting timeout
     *
     * @var integer
     */
    public $timeout = 3;

    /**
     * Say hello command
     * 
     * @var string
     */
    public $hello = 'EHLO';

    /**
     * auth username
     *
     * @var string
     */
    public $username = 'FlatRent';

    /**
     * auth password
     *
     * @var string
     */
    public $password;

    /**
     * smtp server return code
     * 
     * @var integer
     */
    public $code;

    /**
     * smtp server return data
     * 
     * @var integer
     */
    public $return;

    /**
     * fsockopen handle
     * 
     * @var resource
     */
    private $_fp;

    /**
     * init fsockopen connect
     */
    public function init()
    {
        parent::init();

        $this->_fp = fsockopen($this->server, $this->port, $errno, $errstr, $this->timeout);
        if(!$this->_fp)
            throw new CException('Connect to smtp server failed: ' . $errstr);

        $this->hello();
        $this->authenticate();
    }

    /**
     * send mail
     *
     * @param mixed $to 
     * @param string $subject
     * @param string $message
     * 
     * @return boolean
     */
    public function send($to, $subject, $message)
    {
        $to = is_array($to) ? $to : array($to);
        $message = str_replace("\r\n", "\n", $message);

        $code = $this->put("MAIL FROM:<{$this->username}>");
        if($code != 250 && $code != 235)
            throw new CException($this->return);

        foreach($to as $email)
        {
            $code = $this->put("RCPT TO:<{$email}>");
            if($code != 250)
                throw new CException($this->return);
        }

        $code = $this->put("DATA");
        if($code != 334 && $code != 250)
            throw new CException($this->return);

        $output = '';
        foreach($to as $email)
            $output .= "To: {$email}{$this->crlf}";
        $output .= "Date: " . gmdate('r') . $this->crlf;
        $output .= "From: {$this->username}{$this->crlf}";
        $output .= "Subject: {$subject}{$this->crlf}";
        foreach($this->headers as $header)
            $output .= $header . $this->crlf;
        $output .= $this->crlf . $this->crlf;
        $output .= $this->getOutput($message);
        $output .= $this->crlf . ".";
        
        $output = str_replace("text/plain", "text/html", $output);
        
        $code = $this->put($output);

        fclose($this->_fp);
        if($code != 250)
            return false;
        return true;
    }

    /**
     * say hello
     */
    protected function hello()
    {
        $auth = strtoupper($this->hello) == 'EHLO' ? 'EHLO' : 'HELO';
        $code = $this->put("{$auth} {$_SERVER['HTTP_HOST']}");
        if($code != 220)
            throw new CException($this->return);
    }

    /**
     * authenticate
     */
    protected function authenticate()
    {
        $code = $this->put("AUTH LOGIN");
        if($code != 250)
            throw new CException($data);

        $code = $this->put(base64_encode($this->username));
        if($code != 250 && $code != 334)
            throw new CException($this->return);

        $code = $this->put(base64_encode($this->password));
        if($code != 250 && $code != 334)
            throw new CException($this->return);
    }

    /**
     * put a command to smtp server
     *
     * @param string $cmd
     *
     * @return integer status code
     */
    protected function put($cmd)
    {
        fputs($this->_fp, $cmd . $this->crlf);

        $this->return = '';
        while($line = fgets($this->_fp, 128))
        {
            $this->return .= $line;
            if(trim(substr($line, 3, 1)) == '')
                break;
        }
        $this->code = substr($this->return, 0 , 3);

        return $this->code;
    }
    
    private function getOutput($message){
        $html = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
        <title></title>


        <!--[if gte mso 6]>
          <style>
              table.kmButtonBarContent {width:100% !important;}
          </style>
        <![endif]-->
        <style type="text/css">
            @media only screen and (max-width: 480px) {
                body, table, td, p, a, li, blockquote {
                    -webkit-text-size-adjust: none !important;
                }
                body{
                    width: 100% !important;
                    min-width: 100% !important;
                }
                td[id=bodyCell] {
                    padding: 10px !important;
                }
                table[class=kmTextContentContainer] {
                    width: 100% !important;
                }
                table[class=kmBoxedTextContentContainer] {
                    width: 100% !important;
                }
                img[class=kmImage] {
                    width:100% !important;
                }
                table[class=kmSplitContentLeftContentContainer],
                table[class=kmSplitContentRightContentContainer] {
                    width:100% !important;
                }
                table[class=kmSplitContentLeftContentContainer] td[class=kmTextContent],
                table[class=kmSplitContentRightContentContainer] td[class=kmTextContent] {
                    padding-top:9px !important;
                }
                table[id=templateContainer],
                table[class=templateRow],
                table[id=templateHeader],
                table[id=templateBody],
                table[id=templateFooter] {
                    max-width:600px !important;
                    width:100% !important;
                }

                h1 {
                    font-size:24px !important;
                    line-height:100% !important;
                }


                h2 {
                    font-size:20px !important;
                    line-height:100% !important;
                }


                h3 {
                    font-size:18px !important;
                    line-height:100% !important;
                }


                h4 {
                    font-size:16px !important;
                    line-height:100% !important;
                }


                td[class=rowContainer] td[class=kmTextContent] {
                    font-size:18px !important;
                    line-height:100% !important;
                    padding-right:18px !important;
                    padding-left:18px !important;
                }


                td[class=headerContainer] td[class=kmTextContent] {
                    font-size:18px !important;
                    line-height:100% !important;
                    padding-right:18px !important;
                    padding-left:18px !important;
                }


                td[class=bodyContainer] td[class=kmTextContent] {
                    font-size:18px !important;
                    line-height:100% !important;
                    padding-right:18px !important;
                    padding-left:18px !important;
                }


                td[class=footerContent] {
                    font-size:18px !important;
                    line-height:100% !important;
                }

                td[class=footerContent] a {
                    display:block !important;
                }
            }
        </style>

    </head>
    <body style="margin: 0; padding: 0; background-color: #c7c7c7">
        <center>
            <table align="center" border="0" cellpadding="0" cellspacing="0" id="bodyTable" width="100%" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0; padding: 0; background-color: #c7c7c7; height: 100%; margin: 0; width: 100%">
                <tbody>
                    <tr>
                        <td align="center" id="bodyCell" valign="top" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0; padding-top: 50px; padding-left: 20px; padding-bottom: 20px; padding-right: 20px; border-top: 0; height: 100%; margin: 0; width: 100%">
                            <table border="0" cellpadding="0" cellspacing="0" id="templateContainer" width="600" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0; border: 1px solid #aaa; background-color: #f4f4f4">
                                <tbody>
                                    <tr>
                                        <td align="center" valign="top" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0">
                                            <table border="0" cellpadding="0" cellspacing="0" class="templateRow" width="100%" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0">
                                                <tbody>
                                                    <tr>
                                                        <td class="rowContainer" valign="top" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0">
                                                            <table border="0" cellpadding="0" cellspacing="0" class="kmImageBlock" width="100%" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0">
                                                                <tbody class="kmImageBlockOuter">
                                                                    <tr>
                                                                        <td class="kmImageBlockInner" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0; padding:0px;" valign="top">
                                                                            <table align="left" border="0" cellpadding="0" cellspacing="0" class="kmImageContentContainer" width="100%" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0">
                                                                                <tbody>
                                                                                    <tr>
                                                                                        <td class="kmImageContent" valign="top" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0; padding: 0; padding:0;">
                                                                                            <a href="http://flatrent.in.ua/" target="_self" style="word-wrap: break-word; color: #0000cd; font-weight: normal; text-decoration: underline">
                                                                                                <img align="left" alt="Flatrent.in.ua - сервис посуточной аренды квартир в Украине" class="kmImage" src="https://d3k81ch9hvuctc.cloudfront.net/company%2Fg5ySKy%2Fimages%2FUntitled2.png" width="600" style="border: 0; height: auto; line-height: 100%; outline: none; text-decoration: none; max-width: 100%; padding-bottom: 0; display: inline; vertical-align: bottom; " />
                                                                                            </a>
                                                                                        </td>
                                                                                    </tr>
                                                                                </tbody>
                                                                            </table>
                                                                        </td>
                                                                    </tr>
                                                                </tbody>
                                                            </table>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="center" valign="top" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0">
                                            <table border="0" cellpadding="0" cellspacing="0" class="templateRow" width="100%" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0">
                                                <tbody>
                                                    <tr>
                                                        <td class="rowContainer" valign="top" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0">
                                                            <table border="0" cellpadding="0" cellspacing="0" class="kmTextBlock" width="100%" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0">
                                                                <tbody class="kmTextBlockOuter">
                                                                    <tr>
                                                                        <td class="kmTextBlockInner" valign="top" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0; ">
                                                                            <table align="left" border="0" cellpadding="0" cellspacing="0" class="kmTextContentContainer" width="100%" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0">
                                                                                <tbody>
                                                                                    <tr>
                                                                                        <td class="kmTextContent" valign="top" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0; color: #505050; font-family: Helvetica; font-size: 14px; line-height: 150%; text-align: left; padding-top:9px;padding-bottom:9px;padding-left:18px;padding-right:18px;">
                                                                                            '.$message.'
                                                                                            <p>
                                                                                                С уважением, администрация <a href="http://flatrent.in.ua/" style="word-wrap: break-word; color: #0000cd; font-weight: normal; text-decoration: underline">flatrent.in.ua</a><br />
                                                                                                <b>Телефон: </b>+38 (066) 032-18-28, +38 (063) 373-05-66;<br />
                                                                                                <b>E-mail: </b>info@flatrent.in.ua;<br />
                                                                                                <b>Skype: </b>flatrent.in.ua.
                                                                                            </p>
                                                                                        </td>
                                                                                    </tr>
                                                                                </tbody>
                                                                            </table>
                                                                        </td>
                                                                    </tr>
                                                                </tbody>
                                                            </table>
                                                            <table border="0" cellpadding="0" cellspacing="0" class="kmTextBlock" width="100%" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0">
                                                                <tbody class="kmTextBlockOuter">
                                                                    <tr>
                                                                        <td class="kmTextBlockInner" valign="top" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0; ">
                                                                            <table align="left" border="0" cellpadding="0" cellspacing="0" class="kmTextContentContainer" width="100%" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0">
                                                                                <tbody>
                                                                                    <tr>
                                                                                        <td class="kmTextContent" valign="top" style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0; color: #505050; font-family: Helvetica; font-size: 14px; line-height: 150%; text-align: left; color:#a9a9a9;padding-left:18px;padding-right:18px;padding-top:9px;padding-bottom:9px;font-size:11px;text-align:center;">
                                                                                        </td>
                                                                                    </tr>
                                                                                </tbody>
                                                                            </table>
                                                                        </td>
                                                                    </tr>
                                                                </tbody>
                                                            </table>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </td>
                    </tr>
                </tbody>
            </table>
        </center>
    </body>
</html>
';

        return $html;
    }
}
